<template>
	<view class="">
		<uv-upload
			:action="murl"
			:header="header"
			:form-data="formData"
			:maxCount="uploadType == 1 ? maxCount : 1"
			multiple
			:accept="fileType"
			:width="width"
			:height="height"
			:fileList="fileList1"
			@afterRead="afterRead"
			@delete="deletePic"
			:disabled="disabled"
			:size-type="['compressed']"
			:custom-btn="true"
			:show-progress="showProgress"
			name="1"
			:deletable="deletable"
			:index="index">
			<!-- <image :src="addBtnImage" v-if="uploadType == 2" style="width: 330rpx; height: 200rpx;" mode="aspectFill"></image> -->

			<!--			<view >-->
			<!--				<image v-if="uploadType==1" style="width: 200rpx; height: 200rpx;" :src="addBtnImage" mode="aspectFill">-->
			<!--				</image>-->
			<!--				<image v-else-if="uploadType==2" style="width: 330rpx; height: 200rpx;" :src="addBtnImage"-->
			<!--					mode="aspectFill"></image>-->
			<!--			</view>-->
		</uv-upload>
	</view>
</template>

<script>
	import { AddOss } from '@/api/system/oss';
	import { getToken } from '@/utils/auth';
	import { deepClone } from '@/uni_modules/uv-ui-tools/libs/function';
	import { listByIds, delOss } from '@/api/system/oss';

	export default {
		data() {
			return {
				murl: AddOss,
				header: {
					userType: '',
					token: '',
					tenantId: '',
					userId: '',
				},
				formData: {
					files: 'image',
					resPath: 'car_doc',
				},
				name: 'files',
				resultList: [],
				resultObjList: [],
				fileList1: [],
			};
		},
		computed: {
			fileType() {
				//all | media | image | file | video
				return this.upType == 2
					? 'all'
					: this.upType == 1
					? 'file'
					: 'image';
			},
		},
		watch: {
			value: {
				deep: true,
				immediate: true,
				async handler(val) {
					if (val) {
						// 首先将值转为数组
						let list;
						if (Array.isArray(val)) {
							list = deepClone(val);
						} else {
							await listByIds(val).then(res => {
								list = res.data;
							});
						}

						// 然后将数组转为对象数组
						this.fileList1 = list.map(item => {
							// 此处name使用ossId 防止删除出现重名
							item = {
								message: '',
								size: 52363,
								status: 'success',
								thumb: item.url,
								name: item.ossId,
								url: item.url,
								ossId: item.ossId,
								fileName: item.originalName,
							};
							return item;
						});
					} else {
						this.fileList1 = [];
					}
				},
			},
		},

		props: {
			value: {
				type: [String, Object, Array],
				default: () => {
					return [];
				},
			},
			upType: {
				type: Number,
				default: 0, //0图片 1文件  2图片+文件
			},
			//1.普通上传 2.证件上传
			uploadType: {
				type: [String, Number],
				default: 1,
			},
			addBtnImage: {
				type: String,
				default: '../../static/common/addBtn.png',
			},
			maxCount: {
				type: [String, Number],
				default: 99,
			},
			// 内部预览图片区域和选择图片按钮的区域宽度
			width: {
				type: [String, Number],
				default: '200rpx',
			},
			// 内部预览图片区域和选择图片按钮的区域高度
			height: {
				type: [String, Number],
				default: '200rpx',
			},
			//  是否显示进度条
			showProgress: {
				type: Boolean,
				default: true,
			},
			// 是否展示删除按钮
			deletable: {
				type: Boolean,
				default: true,
			},
			//禁用，默认false
			disabled: {
				type: Boolean,
				default: false,
			},
			// 允许上传的图片后缀
			limitType: {
				type: Array,
				default() {
					// 支付宝小程序真机选择图片的后缀为"image"
					// https://opendocs.alipay.com/mini/api/media-image
					return ['png', 'jpg', 'jpeg', 'webp', 'gif', 'image'];
				},
			},
			// 在各个回调事件中的最后一个参数返回，用于区别是哪一个组件的事件
			index: {
				type: [Number, String],
				default: '',
			},
			tag: {
				type: [Number, String],
				default: '',
			},
			objType: {
				type: [Number, String],
				default: '',
			},
		},

		methods: {
			resetAndEmitList() {
				this.resultList = [];
				this.resultObjList = [];

				for (let item of this.fileList1) {
					// this.resultList.push(this.baseImgUrl+item.url);
					this.resultList.push(item.ossId);

					// this.resultObjList.push({
					// 	sysAccessoryId: '',
					// 	id: '',
					// 	// url: this.baseImgUrl+item.url,
					// 	url: item.url,
					// 	objId: '',
					// 	objType: this.objType,
					// 	typeFile: '1',
					// 	nameFile: '',
					// });

					this.resultObjList.push({
						...item,
						url: item.url,
						objType: this.objType,
						typeFile: '1',

						nameAccessory: item.name_accessory ?? null,
						nameDesc: item.name_desc ?? null,
						nameExt: item.name_ext ?? null,
						nameFile: item.name_file ?? null,
						objId: item.obj_id ?? null,
						operationId: item.operation_id ?? null,
						operationName: item.operation_name ?? null,
						sysAccessoryId: item.sys_accessory_id ?? null,
						timeCreate: item.time_create ?? null,
						timeUpdate: item.time_update ?? null,
					});
				}
				// * （1、企业客户 2、供应商，3、收款凭证 4、订单合同附件（无模板）5、退款凭证 6、车辆照片
				// * 7、年检附件 8、交车附件、9维修附件 10、应收款凭证 11、车辆档案12、商业险附件13、换车附件
				// * 14、退车附件 15、交强险 16、渠道商营业执照 17、渠道商法人身份证 18、渠道商附件,19、出险管理
				// * 20、车辆保养,21余额提现22,年检记录附件23、车辆处置附件,24个人客户 49承运险

				// this.$emit('on-change', this.tag, this.resultList, this.resultObjList);
				this.$emit('on-change', this.resultList.join(','));
			},

			// 删除图片
			deletePic(event) {
				delOss(event?.file?.ossId);
				this[`fileList${event.name}`].splice(event.index, 1);
				this.resetAndEmitList();
			},
			// 新增图片
			async afterRead(event) {
				// 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file);
				let fileListLen = this[`fileList${event.name}`].length;
				lists.map(item => {
					this[`fileList${event.name}`].push({
						...item,
						status: 'uploading',
						message: '上传中',
					});
				});
				for (let i = 0; i < lists.length; i++) {
					try {
						const result = await this.uploadFilePromise(
							lists[i].url,
						);

						let item = this[`fileList${event.name}`][fileListLen];
						this[`fileList${event.name}`].splice(
							fileListLen,
							1,
							Object.assign(item, {
								status: 'success',
								message: '',
								url: result.url,
								ossId: result.ossId,
							}),
						);
						fileListLen++;
					} catch (e) {
						uni.showToast({
							title: e,
							icon: 'error',
						});

						this[`fileList${event.name}`].splice(fileListLen, 1, {
							status: 'fail',
							message: '',
							url: '',
							ossId: '',
						});
						fileListLen++;
					}
				}

				this[`fileList${event.name}`] = this[
					`fileList${event.name}`
				].filter(item => item.status !== 'fail');
				this.resetAndEmitList();
			},
			uploadFilePromise(url) {
				return new Promise((resolve, reject) => {
					let a = uni.uploadFile({
						url: this.murl, // 仅为示例，非真实的接口地址
						filePath: url,
						header: {
							Authorization: 'Bearer ' + getToken(),
							'content-type': 'multipart/form-data',
						},
						name: 'file',
						timeout: 7000,
						formData: this.formData,
						success: res => {
							if (res.statusCode == '200') {
								let data = JSON.parse(res.data);
								resolve(data.data);
							} else {
								reject('上传失败');
							}
						},
						fail: e => {
							reject(e.errMsg);
						},
					});
				});
			},
		},
	};
</script>

<style></style>
